<?php

class Core_Controller_Plugin_Route extends Zend_Controller_Plugin_Abstract {
	
	public function routeStartup(Zend_Controller_Request_Abstract $request) 
	{		
		$this->initLanguage();
		$this->installRouter();
		$this->defineRouter();		
	}
	
	private function initLanguage()
	{		
		$locale = new Zend_Locale ();
		$options = array ('scan' => Zend_Translate::LOCALE_FILENAME, 'separator' => '=' );
		$translate = new Zend_Translate (array(	'adapter' => 'ini', 
												'content' => APP_PATH . DS .'/languages',
												'scan' =>Zend_Translate::LOCALE_FILENAME) );
		
		$language = 'vi';
		if (! $translate->isAvailable ( $language )) {
			throw new Zend_Controller_Action_Exception ( 'This page dont exist', 404 );
		} else {
			$locale->setLocale ( $language );
			$translate->setLocale ( $locale );			
			Zend_Registry::set ( 'lang', $locale->getLanguage () );
			Zend_Registry::set ( 'Zend_Locale', $locale );
			Zend_Registry::set ( 'Zend_Translate', $translate );
			Zend_Form::setDefaultTranslator($translate);
		}
	}
	
	private function defineRouter()
	{
		$objView = new Zend_View();
		$skey = $objView->translate('seo_admin_index');	
		$this->addRouter('seo_admin_index', $skey, array(), 'index', 'index', 'admin');		
	}
	
	private function addRouter($sRouteName, $sRegex, $arrRef, $sControllName, $sAction, $sModule='default'){
		$router = Zend_Controller_Front::getInstance()->getRouter();		
		$router->addRoute($sRouteName,
			new Zend_Controller_Router_Route_Regex(
								$sRegex,
                                 array(
                                        'module'=>$sModule,
                                        'controller' => $sControllName,
                                        'action' => $sAction),
                                 $arrRef,
                                 '%s.html'      
			)
		);
	}
	
	private function installRouter()
	{
		$objFront = Zend_Controller_Front::getInstance();
		$router = $objFront->getRouter();
		
		# add default router
		$routeDefault = new Zend_Controller_Router_Route_Module(
				array(),
				$objFront->getDispatcher(),
				$objFront->getRequest()
		);
		
		// Add both language route chained with default route and
		// plain language route
		$router->addRoute('default', $routeDefault);		
	}
	
	public function routeShutdown(Zend_Controller_Request_Abstract $request) 
	{
		$sCurrentRouter=Zend_Controller_Front::getInstance()->getRouter()->getCurrentRouteName();
		Zend_Registry::set('CurrentRoute',$sCurrentRouter);
	}
	
}


